import { Component, inject, OnInit } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { NzFormModule } from 'ng-zorro-antd/form';
import { SharedModule } from '../shared/shared.module';
import { NzInputModule } from 'ng-zorro-antd/input';
import { signResultCreateStyleOptions } from '@proxy/results';
import { SettingDto, SettingService } from '@proxy/settings';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { finalize } from 'rxjs';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { ConfigStateService } from '@abp/ng.core';


@Component({
  selector: 'app-settings',
  templateUrl: './settings.component.html',
  styleUrl: './settings.component.scss',
  standalone: true,
  imports: [NzFormModule, ReactiveFormsModule, SharedModule, NzInputModule, NzSelectModule, NzButtonModule]
})
export class SettingsComponent implements OnInit {

  private _fb: FormBuilder = inject(FormBuilder);
  form = this.createForm();
  private _settingService = inject(SettingService);
  private _stateService = inject(ConfigStateService);

  saving = false;

  get signResultCreateStyleOptions() {
    return signResultCreateStyleOptions;
  }

  ngOnInit(): void {
    this.load();
  }

  load() {
    this._settingService.get().subscribe((setting) => this.buildForm(setting));
  }

  save() {
    this.saving = true;
    const setting = this.form.value as SettingDto;
    this._settingService.update(setting)
      .pipe(finalize(() => {
        this.saving = false;
        this._stateService.refreshAppState();
      }))
      .subscribe((setting) => {
        this.buildForm(setting);
      });
  }

  buildForm(setting: SettingDto) {
    this.form = this.createForm(setting);
  }

  createForm(setting?: SettingDto) {
    const appTitle = setting?.appTitle;
    const signResultCreateStyle = setting?.resultCreateStyle;
    return this._fb.group({
      appTitle: [appTitle, Validators.required],
      signResultCreateStyle: [signResultCreateStyle, Validators.required]
    });
  }
}
